package org.dei.perla.sys.console.core;

import java.net.ServerSocket;
import java.net.Socket;

import org.dei.perla.utils.MultiPlexedPipe;
import org.dei.perla.utils.logger.Logger;
import org.dei.perla.utils.pipe.Pipe;


/**
 * Classe per implementare la console
 * @author Diego
 */
public class ConsoleServer  extends Thread {
	
	//TODO Spostarlo nella config di PerLa
	public final static int PORT = 14567;
	
	private ServerSocket serverSocket;
	private MultiPlexedPipe<String> clientIncomingQueriesPipe;

	public ConsoleServer(){
		clientIncomingQueriesPipe = new MultiPlexedPipe<String>("queryPipe");
	}
	
	public Pipe<String> getQueryToParsePipe() {
		return clientIncomingQueriesPipe.getMultiplexedPipe();
	}
	

	public void run(){
		try 
		{
			serverSocket = new ServerSocket(PORT);
			while(true){
				System.out.println("SERVER: accepting.... \n");
				Socket tClientSocket = serverSocket.accept();
				System.out.println("SERVER: accepted, creo thread \n");
				ServerThread thread = new ServerThread(tClientSocket);
				clientIncomingQueriesPipe.addPipe(thread.getQueryToInjectPipe());
				thread.start();
			}
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}	
	}
}
